import React from "react";
import { DragSource, DropTarget } from "react-dnd";
import { getEmptyImage } from "react-dnd-html5-backend";
import DropWidgetLine from "./drop-widget-line";
import DropDragItem from "../sub-form-source/drop-drag-item";
import { messages } from "share/common";
import { findDOMNode } from "react-dom";
import { Icon } from "antd";

class DropDragFormList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      subHoverIndex: -2,
      lastSubHoverIndex: -3, //上次拖拽的index值，与hoverIndex比较判断，用于减少页面渲染、

      nowSelectedIndex: -1,
    };
  }

  componentDidMount() {
    //链接拖拽的预览图片，用官方api给定一个空图片
    this.props.connectDragPreview(getEmptyImage(), {
      captureDraggingState: true,
    });
  }

  handleClick = (level, subIndex) => {
    this.setState({
      nowSelectedIndex: subIndex,
      subHoverIndex: -2,
      lastSubHoverIndex: -3,
    });
    this.props.onClick(level, this.props.index, subIndex);
  };

  /**
   * 拖拽在内部控件上方时检查
   * @param hoverIndex 拖拽的组件正好在第hoverIndex个控件上方
   */
  handleHover = (subHoverIndex) => {
    let { lastSubHoverIndex } = this.state;
    //console.log("....handleHover subHoverIndex ", subHoverIndex);
    //console.log("....handleHover lastSubHoverIndex ", lastSubHoverIndex);
    //如果跟上次一样，则不刷新视图
    if (subHoverIndex !== lastSubHoverIndex) {
      this.setState({ subHoverIndex, lastSubHoverIndex: subHoverIndex });
      let { index, widget } = this.props;
      this.props.onSubHover(widget, index, subHoverIndex);
    }
  };

  /**
   * widget-item 拖拽在组件上方时检查调用
   */
  checkHoverIndex = () => {
    let { subHoverIndex, lastSubHoverIndex } = this.state;
    let { widgetList } = this.state;
    let result = -1;
    //如果为-1，则代表列表为空或者拖拽处没有widget组件，代表在列表最后
    if (subHoverIndex === -1) {
      result = widgetList.length;
    } else {
      //否则就是对应的序列值
      result = subHoverIndex;
    }
    //如果跟上次一样，则不刷新视图
    if (subHoverIndex !== lastSubHoverIndex) {
      this.setState({
        hoverIndex: result,
        lastHoverIndex: result,
      });
    }
  };

  renderDeleteIcon = (children, subIndex) => {
    const { index, deleteEnabled, nowSelectedSubIndex, className } = this.props;
    if (deleteEnabled && className === "selected") {
      return (
        <div>
          {nowSelectedSubIndex === subIndex && !children[nowSelectedSubIndex].readonly && (
            <div
              className={`widget-delete ${children[nowSelectedSubIndex].messageKey === "table" && "not-center"}`}
              onClick={() => this.props.onSubWidgetDelete(index, subIndex)}
            >
              <Icon type="delete" />
            </div>
          )}
        </div>
      );
    } else {
      <div></div>;
    }
  };

  render() {
    const { subHoverIndex, nowSelectedIndex } = this.state;

    const { widget, onClick, width, className, isOver, nowSelectedSubIndex } = this.props;
    const { isDragging, connectDropTarget, connectDragSource } = this.props;
    return connectDropTarget(
      connectDragSource(
        <div className={`sub-form-list-view ${className}`}>
          <div className="title" onClick={(e) => this.handleClick("level1", -2)}>
            {widget.fieldName}
          </div>
          <div className="sub-form-list-view-inner">
            <div key={widget.counterFlag} className={`list-sort-widget ${isOver && subHoverIndex === 0 && "hover"}`}>
              <DropWidgetLine
                style={{ marginLeft: "4px" }}
                widget={widget}
                key={"linetips" + widget.messageKey}
                showTips={!widget.children || widget.children.length === 0}
                index={-1}
                onHover={this.handleHover}
              ></DropWidgetLine>
            </div>
            <div className="sub-form-list-content">
              {widget.children &&
                widget.children.map((subWidget, index) => (
                  <div
                    style={{ marginLeft: "4px" }}
                    key={`linehover${subWidget.messageKey}${index}`}
                    className={`list-sort-widget ${isOver && subHoverIndex - 1 === index && "hover"}`}
                  >
                    <DropDragItem
                      widget={subWidget}
                      key={`line${subWidget.messageKey}${index}`}
                      index={index}
                      onHover={this.handleHover}
                      className={className === "selected" && nowSelectedSubIndex === index ? "selected" : ""}
                      onClick={(e) => this.handleClick("level2", index)}
                    />
                    {this.renderDeleteIcon(widget.children, index)}
                  </div>
                ))}
            </div>
          </div>
          <div className="tips3" onClick={(e) => this.handleClick("level1", -2)}>
            +{messages("common.add") /*添加*/}
          </div>
        </div>
      )
    );
  }
}

DropDragFormList.propTypes = {
  connectDropTarget: React.PropTypes.func.isRequired,
  connectDragSource: React.PropTypes.func.isRequired, //自动注入
  connectDragPreview: React.PropTypes.func.isRequired, //自动注入
  isOver: React.PropTypes.bool.isRequired,
  widget: React.PropTypes.object,
  width: React.PropTypes.any, //组件宽度，默认100%
  onClick: React.PropTypes.func,
  className: React.PropTypes.string, //内部组件的className
  index: React.PropTypes.number, //包装后的标记列表顺序，当有新控件hover时返回顺序
  deleteEnabled: React.PropTypes.bool, //是否可以删除
  onSubWidgetDelete: React.PropTypes.func,
};

export default DropTarget(
  "widget-item",
  {
    //hover时得到对应的index返回给上级
    hover(props, monitor, component) {},
  },
  (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
  })
)(
  DragSource(
    "widget-item",
    {
      beginDrag(props) {
        return props.widget;
      },
    },
    (connect, monitor) => ({
      connectDragSource: connect.dragSource(),
      connectDragPreview: connect.dragPreview(),
      isDragging: monitor.isDragging(),
    })
  )(DropDragFormList)
);
